<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <!-- 基本信息 -->
          <a-collapse-panel key="1" header="基本信息">
        <a-row :gutter="48">
           <a-col :span="8" :hidden="true">
              <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
                <a-input placeholder="请输入标题" :disabled="formDisabled" v-model="model.bpmBizTitle"></a-input>
              </a-form-model-item>
            </a-col>

            <a-col :span="8">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billNo">
              <a-input :disabled=formDisabled v-model="model.billNo" placeholder="请输入单据编号" disabled ></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
             <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
                  <select-user-by-dep   :multi="false" v-model="model.proposer" disabled></select-user-by-dep>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
              <a-input v-model="model.createTime" placeholder="请输入申请日期" disabled ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposerDeptId">
                  <j-select-depart :disabled="formDisabled" v-model="model.proposerDeptId" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
                  <select-team-input
                  :disabled=formDisabled
                  v-model="model.teamId" :tdlx="3"/>
            </a-form-model-item>
          </a-col>
          
          
          <a-col :span="8">
            <a-form-model-item label="购买金额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseMoney">
              <a-input-number :disabled=formDisabled :max="99999999" :min="0"  v-model="model.purchaseMoney" placeholder="请输入购买金额" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="购买日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseDate">
              <j-date :disabled=formDisabled placeholder="请选择购买日期" v-model="model.purchaseDate"  style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="原办公电脑处理方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="oldComputerProcessMode">
              <j-dict-select-tag :disabled=formDisabled type="list" v-model="model.oldComputerProcessMode" dictCode="old_computer_process_mode" placeholder="请选择原办公电脑处理方式" @input="gradesBlur"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="接收团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="receiveTeam"  v-if="model.oldComputerProcessMode == '1'">
              <!-- <a-input :disabled=formDisabled v-model="model.receiveTeam" placeholder="请输入接收团队"  ></a-input> -->
              <select-team-input
                  :disabled=formDisabled
                  v-model="model.receiveTeam" :tdlx="3"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="接收人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="receivePeople"  v-if="model.oldComputerProcessMode == '1'">
              <!-- <a-input :disabled=formDisabled v-model.number="model.receivePeople" placeholder="请输入接收人" ></a-input> -->
              <select-user-by-dep :disabled=formDisabled   :multi="false" v-model="model.receivePeople" ></select-user-by-dep>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.remark" rows="4" placeholder="请输入备注"/>
            </a-form-model-item>
          </a-col>
        </a-row>
          </a-collapse-panel>

          <a-collapse-panel key="3" header="电脑明细">
            <a-row :gutter="48">
              <ErpComputerPurchaseDetailList ref="purchaseApply" :disabled="formDisabled" />
            </a-row>
          </a-collapse-panel>

        <a-collapse-panel key="2" header="附件信息（发票、购买记录）">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item prop="attachments">
                  <j-upload  :disabled="formDisabled" v-model="model.attachments"></j-upload>
                  <!-- <a-button v-else icon="download" @click="viewFile(model.attachments)">文件列表</a-button> -->
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
    </j-form-container>
    <a-row :gutter="48" v-if="formBpm">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary"  @click="onPrint">打印</a-button>
      </a-col>
    </a-row>
    <!-- <view-file-modal ref="viewFileModal"></view-file-modal> -->
    <ErpComputerPurchaseFormPrint v-if="formBpm" class="print_style" id="computerContent" :formData="model" :formDataHistory="formData"></ErpComputerPurchaseFormPrint>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  // import { viewFile } from '@/utils/util'
  // import ViewFileModal from '@/views/scy/components/ViewFileModal'
  import { mapGetters } from 'vuex';
  import moment from 'moment';
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
  import ErpComputerPurchaseDetailList from '@/views/erp/workbench/computerPurchase/ErpComputerPurchaseDetailList'
  import CommonFlowList from '@/views/components/CommonFlowList.vue';
  import Print from '@/utils/print/printarea.js';
  import ErpComputerPurchaseFormPrint from './ErpComputerPurchaseFormPrint.vue'; // 打印定制
  export default {
    name: 'ErpComputerPurchaseForm',
    components: {
      // ViewFileModal,
      SelectTeamInput,
      SelectUserByDep,
      ErpComputerPurchaseDetailList,
      CommonFlowList,
      ErpComputerPurchaseFormPrint
    },
    // mixins: [viewFile],
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {

      var validatorDate = async (rule,value,callback)=>{
        if(value){
          const that = this;
          if( Date.parse(that.model.purchaseDate) <  Date.parse(that.getDate(that.model.createTime))){
            callback('购买日期不能早于申请日期!')
            return;
          }
          callback()
        }
        callback()
      };
      return {
        activeKey: ['1', '2', '3'],
        model:{
         },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        validatorRules: {
          bpmBizTitle:[
            { required: true, message: '请输入标题!' }
          ],
          // purchaseMoney: [
          //     { required: true, pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入购买金额!' },
          // ],
          // purchaseDate: [
          //     { required: true, message: '请选择购买日期!',trigger: 'change'},
          //     { validator: validatorDate, trigger: "change" }
          // ],
          createTime: [
              { required: true, message: '请选择申请日期!',trigger: 'change'},
          ],
          // oldComputerProcessMode: [
          //     { required: true, message: '请选择原办公电脑处理方式!',trigger: 'blur'},
          // ],
          // receiveTeam: [
          //     { required: true, message: '选择接收团队!',trigger: 'change'},
          // ],
          // receivePeople: [
          //     { required: true, message: '请选择接收人!',trigger: 'change'},
          // ],
          // proposer: [
          //     { required: true, message: '请选择申请人!',trigger: 'change'},
          // ],
          // proposerDeptId: [
          //     { required: true, message: '请选择申请人部门!',trigger: 'change'},
          // ],
        purchaseMoney: [
            { required: true, pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入采购金额!' },
        ],
        purchaseDate: [
            { required: true, message: '请选择购买日期!',trigger: 'change'},
            { validator: validatorDate, trigger: "change" }
        ],
        oldComputerProcessMode: [
            { required: true, message: '请选择原办公电脑处理方式!',trigger: 'blur'},
        ],
        receiveTeam: [
            { required: true, message: '请选择接收团队!',trigger: 'change'},
        ],
        receivePeople: [
            { required: true, message: '请选择接收人!',trigger: 'change'},
        ],
        proposer: [
            { required: true, message: '请选择申请人!',trigger: 'change'},
        ],
        proposerDeptId: [
            { required: true, message: '请选择申请人部门!',trigger: 'change'},
        ],
        teamId: [
            { required: true, message: '请选择所属团队!',trigger: 'change'},
        ],
        },
        url: {
          add: "/api/erp/workbench/article/erpComputerPurchase/add",
          edit: "/api/erp/workbench/article/erpComputerPurchase/edit",
          queryById: "/api/erp/workbench/article/erpComputerPurchase/queryById",
          gainBillNo: "/api/erp/workbench/article/erpComputerPurchase/getBillNo"
        },
        userName: ''
      }
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      ...mapGetters(['userInfo']),
      add () {
        this.edit(this.modelDefault);
        this.userName = this.userInfo().empName;// 当前登录人名称
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
        this.model.proposerDeptId = this.userInfo().deptId; //当前登录人部门
        this.model.proposer = this.userInfo().empId; //获取经办人id
        this.getBillNo();
      },
      backUserInfo(data) {
          // this.model.applyUnit = data[0].orgDepart;//申请人单位
          this.model.applyDept = data[0].departmentId;//申请人部门
      },
      //生成单据编号
      getBillNo () {
        getAction(this.url.gainBillNo).then((res)=>{
          if(res.success){
            //that.model.billNo = res.result//单据编号
            this.$set(this.model,'billNo',res.result)
            //流程标题添加
            this.$set(this.model,'bpmBizTitle',this.userName + '-' + this.model.billNo);
          }
        })
      },
      getDate(date){
        var year = date.substr(0,4);//substr()是从0开始计算的
        var month = date.substr(5,2);//月份是0到11个月
        var day = date.substr(8,2);
        // alert();
        return year+"-"+month+"-"+day;
      },
      //接收人团队和接收人置空
      gradesBlur(){
        this.$set(this.model,'receiveTeam','')
        this.$set(this.model,'receivePeople','')
      },
      oldComputerProcessModeRule(){
        if(this.modal.oldComputerProcessMode == 1){
          return true;
        }else {
          return false;
        }
      },
      edit (record) {
        this.$refs.form.resetFields();
        this.model = Object.assign({}, record);
        if (this.model.id) {
          this.$refs.purchaseApply.loadData(1, this.model.id)
        } else {
          this.$refs.purchaseApply.dataSource = []
        }
        this.visible = true;
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          });
        }
      },
      submitForm () {
        let details = this.$refs.purchaseApply.submitForm()
        const that = this;


        if(!details.length > 0) {
          this.$message.warning('请添加电脑明细信息！');
          this.$emit('unButtonDisable');
          return
        }
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            this.model.detailList = details
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
                that.$emit('unButtonDisable');
              }
            }).catch((error)=>{
              that.$emit('unButtonDisable');
            }).finally(() => {
              that.confirmLoading = false;
            })
          }else{
            that.$emit('unButtonDisable');
          }

        })
      },

      // 点击打印
      onPrint () {
        let print = new Print({
          el: '#computerContent',
          popTitle: '笔记本采购申请详情 · 禾美环保',
          endCallback() {

          }
        })
      }
    }
  }
</script>